<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>管理后台 - 水果超市</title>
  <link rel="stylesheet" href="/css/style.css">
  <style>
    .tabs {
      display: flex;
      border-bottom: 2px solid #e4e7ed;
      margin-bottom: 20px;
    }
    .tab {
      padding: 10px 20px;
      cursor: pointer;
      border: none;
      background: none;
      font-size: 14px;
      color: #606266;
      transition: all 0.3s;
    }
    .tab:hover {
      color: #409eff;
    }
    .tab.active {
      color: #409eff;
      border-bottom: 2px solid #409eff;
      margin-bottom: -2px;
    }
    .tab-content {
      display: none;
    }
    .tab-content.active {
      display: block;
    }
    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
      z-index: 1000;
    }
    .modal.active {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .modal-content {
      background-color: white;
      padding: 30px;
      border-radius: 8px;
      max-width: 600px;
      width: 90%;
      max-height: 80vh;
      overflow-y: auto;
    }
    .modal-header {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .modal-footer {
      margin-top: 20px;
      text-align: right;
    }
    /* 促销详情样式 */
    .detail-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      line-height: 1.6;
    }
    .detail-label {
      font-weight: 600;
      color: #333;
      min-width: 120px;
      flex-shrink: 0;
    }
    .detail-value {
      color: #666;
      flex: 1;
    }
  </style>
</head>
<body>
  <div id="app" v-cloak>
    <!-- 页面头部 -->
    <div class="header">
      <div class="container clearfix">
        <h1>⚙️ 管理后台</h1>
        <div class="header-actions">
          <a href="/index.html" class="btn btn-default">返回首页</a>
          <a href="/cart.html" class="btn btn-default">🛒 购物车</a>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="container">
      <!-- Tab导航 -->
      <div class="tabs">
        <button 
          class="tab"
          :class="{ active: activeTab === 'products' }"
          @click="activeTab = 'products'"
        >
          商品管理
        </button>
        <button 
          class="tab"
          :class="{ active: activeTab === 'pricelists' }"
          @click="activeTab = 'pricelists'"
        >
          价目表管理
        </button>
        <button 
          class="tab"
          :class="{ active: activeTab === 'promotions' }"
          @click="activeTab = 'promotions'"
        >
          促销规则管理
        </button>
        <button 
          class="tab"
          :class="{ active: activeTab === 'units' }"
          @click="activeTab = 'units'"
        >
          单位管理
        </button>
      </div>

      <!-- ==================== 商品管理 ==================== -->
      <div class="tab-content" :class="{ active: activeTab === 'products' }">
        <div class="card">
          <div class="card-header clearfix">
            商品列表
            <button class="btn btn-primary" style="float: right;" @click="openProductModal()">
              + 新增商品
            </button>
          </div>
          <div class="card-body">
            <table class="table">
              <thead>
                <tr>
                  <th>商品ID</th>
                  <th>商品名称</th>
                  <th>分类</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="product in products" :key="product.id">
                  <td style="font-family: monospace; font-size: 12px;">{{ product.id }}</td>
                  <td>{{ product.name }}</td>
                  <td>{{ product.category }}</td>
                  <td>
                    <span :class="['badge', product.status === 'ACTIVE' ? 'badge-success' : 'badge-danger']">
                      {{ product.status === 'ACTIVE' ? '上架' : '下架' }}
                    </span>
                  </td>
                  <td>
                    <button class="btn btn-default btn-sm" @click="openProductModal(product)">编辑</button>
                    <button 
                      v-if="product.status === 'ACTIVE'"
                      class="btn btn-warning btn-sm" 
                      @click="delistProduct(product.id)"
                    >
                      下架
                    </button>
                    <button 
                      v-else
                      class="btn btn-success btn-sm" 
                      @click="listProduct(product.id)"
                    >
                      上架
                    </button>
                    <button class="btn btn-danger btn-sm" @click="deleteProduct(product.id)">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- ==================== 价目表管理 ==================== -->
      <div class="tab-content" :class="{ active: activeTab === 'pricelists' }">
        <div class="card">
          <div class="card-header clearfix">
            价目表列表
            <button class="btn btn-primary" style="float: right;" @click="openPriceListModal()">
              + 新增价目表
            </button>
          </div>
          <div class="card-body">
            <table class="table">
              <thead>
                <tr>
                  <th>价目表ID</th>
                  <th>名称</th>
                  <th>生效时间</th>
                  <th>失效时间</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="priceList in priceLists" :key="priceList.id">
                  <td style="font-family: monospace; font-size: 12px;">{{ priceList.id }}</td>
                  <td>{{ priceList.name }}</td>
                  <td>{{ formatDateTime(priceList.effectiveFrom, 'YYYY-MM-DD') }}</td>
                  <td>{{ formatDateTime(priceList.effectiveTo, 'YYYY-MM-DD') }}</td>
                  <td>
                    <span :class="['badge', priceList.status === 'ACTIVE' ? 'badge-success' : 'badge-danger']">
                      {{ priceList.status === 'ACTIVE' ? '已激活' : '未激活' }}
                    </span>
                  </td>
                  <td>
                    <button class="btn btn-default btn-sm" @click="viewPriceListEntries(priceList)">详情</button>
                    <button 
                      v-if="priceList.status !== 'ACTIVE'"
                      class="btn btn-success btn-sm" 
                      @click="activatePriceList(priceList.id)"
                    >
                      激活
                    </button>
                    <button 
                      v-else
                      class="btn btn-warning btn-sm" 
                      @click="deactivatePriceList(priceList.id)"
                    >
                      停用
                    </button>
                    <button
                      v-if="priceList.status !== 'ACTIVE'"
                      class="btn btn-danger btn-sm"
                      @click="deletePriceList(priceList.id)"
                    >
                      删除
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- ==================== 促销规则管理 ==================== -->
      <div class="tab-content" :class="{ active: activeTab === 'promotions' }">
        <div class="card">
          <div class="card-header clearfix">
            促销规则列表
            <button class="btn btn-primary" style="float: right; margin-left: 10px;" @click="openPromotionModal('THRESHOLD_DISCOUNT')">
              + 满减规则
            </button>
            <button class="btn btn-primary" style="float: right;" @click="openPromotionModal('ITEM_DISCOUNT')">
              + 单品折扣
            </button>
          </div>
          <div class="card-body">
            <table class="table">
              <thead>
                <tr>
                  <th>名称</th>
                  <th>类型</th>
                  <th>优先级</th>
                  <th>有效期</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="rule in pricingRules" :key="rule.id">
                  <td>{{ rule.name }}</td>
                  <td>
                    <span class="badge badge-primary">
                      {{ rule.type === 'ITEM_DISCOUNT' ? '单品折扣' : '满减优惠' }}
                    </span>
                  </td>
                  <td>
                    <span class="badge badge-info">{{ getPriorityDescription(rule.priority) }}</span>
                  </td>
                  <td style="font-size: 12px;">
                    {{ formatDateTime(rule.effectiveFrom, 'YYYY-MM-DD') }} 至 
                    {{ formatDateTime(rule.effectiveTo, 'YYYY-MM-DD') }}
                  </td>
                  <td>
                    <span :class="['badge', rule.enabled ? 'badge-success' : 'badge-danger']">
                      {{ rule.enabled ? '启用' : '禁用' }}
                    </span>
                  </td>
                  <td>
                    <button 
                      class="btn btn-primary btn-sm" 
                      @click="openPromotionDetailModal(rule)"
                      style="margin-right: 5px;"
                    >
                      详情
                    </button>
                    <button 
                      v-if="rule.enabled"
                      class="btn btn-warning btn-sm" 
                      @click="disablePricingRule(rule.id)"
                      style="margin-right: 5px;"
                    >
                      禁用
                    </button>
                    <button 
                      v-else
                      class="btn btn-success btn-sm" 
                      @click="enablePricingRule(rule.id)"
                      style="margin-right: 5px;"
                    >
                      启用
                    </button>
                    <button class="btn btn-danger btn-sm" @click="deletePricingRule(rule.id)">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- ==================== 单位管理 ==================== -->
      <div class="tab-content" :class="{ active: activeTab === 'units' }">
        <div class="card">
          <div class="card-header clearfix">
            单位列表
            <button class="btn btn-primary" style="float: right;" @click="openUnitModal()">
              + 新增单位
            </button>
          </div>
          <div class="card-body">
            <table class="table">
              <thead>
                <tr>
                  <th>单位代码</th>
                  <th>单位名称</th>
                  <th>描述</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="unit in units" :key="unit.code">
                  <td style="font-family: monospace;">{{ unit.code }}</td>
                  <td>{{ unit.name }}</td>
                  <td>{{ unit.description }}</td>
                  <td>
                    <button class="btn btn-default btn-sm" @click="openUnitModal(unit)">编辑</button>
                    <button class="btn btn-danger btn-sm" @click="deleteUnit(unit.code)">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- ==================== 商品编辑弹窗 ==================== -->
    <div class="modal" :class="{ active: productModalVisible }">
      <div class="modal-content">
        <div class="modal-header">{{ productForm.id ? '编辑商品' : '新增商品' }}</div>
        <div class="form-group">
          <label class="form-label">商品名称</label>
          <input type="text" class="form-control" v-model="productForm.name">
        </div>
        <div class="form-group">
          <label class="form-label">分类</label>
          <input type="text" class="form-control" v-model="productForm.category">
        </div>
        <div class="form-group">
          <label class="form-label">描述</label>
          <textarea class="form-control" v-model="productForm.description" rows="3"></textarea>
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="productModalVisible = false">取消</button>
          <button class="btn btn-primary" @click="saveProduct">保存</button>
        </div>
      </div>
    </div>

    <!-- ==================== 价目表编辑弹窗 ==================== -->
    <div class="modal" :class="{ active: priceListModalVisible }">
      <div class="modal-content">
        <div class="modal-header">新增价目表</div>
        <div class="form-group">
          <label class="form-label">价目表名称</label>
          <input type="text" class="form-control" v-model="priceListForm.name">
        </div>
        <div class="form-group">
          <label class="form-label">生效日期</label>
          <input type="date" class="form-control" v-model="priceListForm.effectiveFrom">
        </div>
        <div class="form-group">
          <label class="form-label">失效日期（可选）</label>
          <input type="date" class="form-control" v-model="priceListForm.effectiveTo">
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="priceListModalVisible = false">取消</button>
          <button class="btn btn-primary" @click="savePriceList">保存</button>
        </div>
      </div>
    </div>

    <!-- ==================== 促销规则编辑弹窗 ==================== -->
    <div class="modal" :class="{ active: promotionModalVisible }">
      <div class="modal-content">
        <div class="modal-header">
          {{ promotionForm.ruleType === 'ITEM_DISCOUNT' ? '新增单品折扣' : '新增满减规则' }}
        </div>
        <div class="form-group">
          <label class="form-label">规则名称</label>
          <input type="text" class="form-control" v-model="promotionForm.name">
        </div>
        <div class="form-group">
          <label class="form-label">生效时间</label>
          <input type="datetime-local" class="form-control" v-model="promotionForm.effectiveFrom">
        </div>
        <div class="form-group">
          <label class="form-label">失效时间（可选）</label>
          <input type="datetime-local" class="form-control" v-model="promotionForm.effectiveTo">
        </div>
        
        <!-- 单品折扣特有字段 -->
        <template v-if="promotionForm.ruleType === 'ITEM_DISCOUNT'">
          <div class="form-group">
            <label class="form-label">商品</label>
            <select class="form-control" v-model="promotionForm.productId">
              <option value="">请选择商品</option>
              <option v-for="product in activeProducts" :key="product.id" :value="product.id">
                {{ product.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">折扣率（0-1之间，如0.8表示8折）</label>
            <input type="number" class="form-control" v-model.number="promotionForm.discountRate" step="0.01" min="0" max="1">
          </div>
        </template>
        
        <!-- 满减规则特有字段 -->
        <template v-if="promotionForm.ruleType === 'THRESHOLD_DISCOUNT'">
          <div class="form-group">
            <label class="form-label">门槛金额</label>
            <input type="number" class="form-control" v-model.number="promotionForm.thresholdAmount" step="0.01">
          </div>
          <div class="form-group">
            <label class="form-label">优惠金额</label>
            <input type="number" class="form-control" v-model.number="promotionForm.reductionAmount" step="0.01">
          </div>
          <div class="form-group">
            <label class="form-label">是否每满减</label>
            <select class="form-control" v-model="promotionForm.stackable">
              <option :value="false">一次性满减</option>
              <option :value="true">每满减</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">满减门槛判断方式</label>
            <select class="form-control" v-model="promotionForm.thresholdUseOriginalPrice">
              <option :value="false">基于折后价（默认）</option>
              <option :value="true">基于原价</option>
            </select>
            <small class="form-text text-muted">
              • <strong>基于折后价</strong>：先计算单品折扣，再判断是否满足满减（严格按优先级顺序）<br>
              • <strong>基于原价</strong>：用商品原价判断满减，避免客户误解<br>
              例：购物车301元（含草莓13元8折），满300-50。基于原价→触发满减；基于折后价→不触发
            </small>
          </div>
        </template>
        
        <div class="modal-footer">
          <button class="btn btn-default" @click="promotionModalVisible = false">取消</button>
          <button class="btn btn-primary" @click="savePromotion">保存</button>
        </div>
      </div>
    </div>

    <!-- ==================== 单位编辑弹窗 ==================== -->
    <div class="modal" :class="{ active: unitModalVisible }">
      <div class="modal-content">
        <div class="modal-header">{{ unitForm.code ? '编辑单位' : '新增单位' }}</div>
        <div class="form-group">
          <label class="form-label">单位代码</label>
          <input 
            type="text" 
            class="form-control" 
            v-model="unitForm.code"
            :disabled="!!unitForm.code"
            placeholder="如: KG, JIN, GE"
          >
        </div>
        <div class="form-group">
          <label class="form-label">单位名称</label>
          <input type="text" class="form-control" v-model="unitForm.name" placeholder="如: 公斤, 斤, 个">
        </div>
        <div class="form-group">
          <label class="form-label">描述</label>
          <input type="text" class="form-control" v-model="unitForm.description">
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="unitModalVisible = false">取消</button>
          <button class="btn btn-primary" @click="saveUnit">保存</button>
        </div>
      </div>
    </div>

    <!-- ==================== 价格条目管理弹窗 ==================== -->
    <div class="modal" :class="{ active: priceEntryListModalVisible }">
      <div class="modal-content" style="max-width: 800px;">
        <div class="modal-header clearfix">
          价格条目管理 - {{ currentPriceList?.name }}
          <button 
            class="btn btn-primary btn-sm" 
            style="float: right;" 
            @click="openAddEntryModal()"
          >
            + 添加商品
          </button>
        </div>
        <div class="card-body">
          <table class="table">
            <thead>
              <tr>
                <th>商品名称</th>
                <th>单价</th>
                <th>单位</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="priceEntries.length === 0">
                <td colspan="4" style="text-align: center; color: #999;">
                  暂无价格条目，点击"添加商品"开始添加
                </td>
              </tr>
              <tr v-for="entry in priceEntries" :key="entry.id">
                <td>{{ entry.productName || entry.productId }}</td>
                <td>{{ formatMoney(entry.unitPrice?.amount) }}</td>
                <td>{{ entry.baseUnitName || entry.baseUnit }}</td>
                <td>
                  <button 
                    class="btn btn-danger btn-sm" 
                    @click="deletePriceEntry(entry.id)"
                  >
                    删除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="priceEntryListModalVisible = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- ==================== 添加价格条目弹窗 ==================== -->
    <div class="modal" :class="{ active: addPriceEntryModalVisible }">
      <div class="modal-content">
        <div class="modal-header">添加商品到价目表</div>
        <div class="form-group">
          <label class="form-label">选择商品</label>
          <select class="form-control" v-model="priceEntryForm.productId">
            <option value="">请选择商品</option>
            <option v-for="product in activeProducts" :key="product.id" :value="product.id">
              {{ product.name }} ({{ product.category }})
            </option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">单价（元）</label>
          <input 
            type="number" 
            class="form-control" 
            v-model.number="priceEntryForm.unitPrice" 
            step="0.01"
            min="0"
            placeholder="例如: 5.00"
          >
        </div>
        <div class="form-group">
          <label class="form-label">销售单位</label>
          <select class="form-control" v-model="priceEntryForm.baseUnit">
            <option value="">请选择单位</option>
            <option v-for="unit in units" :key="unit.code" :value="unit.code">
              {{ unit.name }}
            </option>
          </select>
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="addPriceEntryModalVisible = false">取消</button>
          <button class="btn btn-primary" @click="savePriceEntry">保存</button>
        </div>
      </div>
    </div>

    <!-- ==================== 促销规则详情弹窗 ==================== -->
    <div class="modal" :class="{ active: promotionDetailModalVisible }">
      <div class="modal-content" style="max-width: 600px;">
        <div class="modal-header">促销规则详情</div>
        
        <div v-if="currentPromotionDetail" class="card-body">
          <!-- 基本信息 -->
          <div style="margin-bottom: 20px;">
            <h4 style="border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-bottom: 15px;">基本信息</h4>
            <div class="detail-row">
              <span class="detail-label">规则名称：</span>
              <span class="detail-value">{{ currentPromotionDetail.name }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">规则类型：</span>
              <span class="badge badge-primary">
                {{ currentPromotionDetail.type === 'ITEM_DISCOUNT' ? '单品折扣' : '满减优惠' }}
              </span>
            </div>
            <div class="detail-row">
              <span class="detail-label">优先级：</span>
              <span class="badge badge-info">{{ getPriorityDescription(currentPromotionDetail.priority) }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">状态：</span>
              <span :class="['badge', currentPromotionDetail.enabled ? 'badge-success' : 'badge-danger']">
                {{ currentPromotionDetail.enabled ? '启用' : '禁用' }}
              </span>
            </div>
            <div class="detail-row">
              <span class="detail-label">有效期：</span>
              <span class="detail-value">
                {{ formatDateTime(currentPromotionDetail.effectiveFrom, 'YYYY-MM-DD HH:mm') }} 
                至 
                {{ formatDateTime(currentPromotionDetail.effectiveTo, 'YYYY-MM-DD HH:mm') }}
              </span>
            </div>
          </div>

          <!-- 单品折扣特有信息 -->
          <div v-if="currentPromotionDetail.type === 'ITEM_DISCOUNT' && currentPromotionDetail.details" style="margin-bottom: 20px;">
            <h4 style="border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-bottom: 15px;">折扣详情</h4>
            <div class="detail-row">
              <span class="detail-label">适用商品：</span>
              <span class="detail-value">
                {{ currentPromotionDetail.details.productName || currentPromotionDetail.details.productId || '未知' }}
              </span>
            </div>
            <div class="detail-row">
              <span class="detail-label">折扣率：</span>
              <span class="detail-value" style="color: #e74c3c; font-weight: bold; font-size: 16px;">
                {{ (currentPromotionDetail.details.discountRate * 10).toFixed(1) }}折
                <span style="color: #666; font-size: 14px; font-weight: normal;">
                  ({{ (currentPromotionDetail.details.discountRate * 100).toFixed(0) }}%)
                </span>
              </span>
            </div>
          </div>

          <!-- 满减规则特有信息 -->
          <div v-if="currentPromotionDetail.type === 'THRESHOLD_DISCOUNT' && currentPromotionDetail.details" style="margin-bottom: 20px;">
            <h4 style="border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-bottom: 15px;">满减详情</h4>
            <div class="detail-row">
              <span class="detail-label">门槛金额：</span>
              <span class="detail-value" style="font-weight: bold;">
                {{ formatMoney(currentPromotionDetail.details.thresholdAmount?.amount) }}
              </span>
            </div>
            <div class="detail-row">
              <span class="detail-label">优惠金额：</span>
              <span class="detail-value" style="color: #e74c3c; font-weight: bold; font-size: 16px;">
                -{{ formatMoney(currentPromotionDetail.details.discountAmount?.amount) }}
              </span>
            </div>
            <div class="detail-row">
              <span class="detail-label">叠加规则：</span>
              <span :class="['badge', currentPromotionDetail.details.stackable ? 'badge-success' : 'badge-info']">
                {{ currentPromotionDetail.details.stackable ? '每满减（可叠加）' : '一次性满减' }}
              </span>
            </div>
            <div class="detail-row">
              <span class="detail-label">门槛判断方式：</span>
              <span class="badge badge-warning">
                {{ currentPromotionDetail.details.thresholdUseOriginalPrice ? '基于原价' : '基于折后价' }}
              </span>
            </div>
            <div v-if="currentPromotionDetail.details.thresholdUseOriginalPrice" class="detail-row" style="margin-top: 10px;">
              <div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 10px; font-size: 13px; color: #856404;">
                <strong>说明：</strong>使用商品原价判断是否满足满减门槛，避免因单品折扣导致的金额变化影响客户体验。
              </div>
            </div>
          </div>

          <!-- 示例说明 -->
          <div v-if="currentPromotionDetail.type === 'THRESHOLD_DISCOUNT' && currentPromotionDetail.details" style="background: #f8f9fa; border-radius: 4px; padding: 15px; font-size: 13px;">
            <strong>💡 示例：</strong>
            <p style="margin: 8px 0 0 0;">
              <span v-if="!currentPromotionDetail.details.stackable && !currentPromotionDetail.details.thresholdUseOriginalPrice">
                购物车总额达到 {{ formatMoney(currentPromotionDetail.details.thresholdAmount?.amount) }}（折后价）时，<span style="color: #e74c3c; font-weight: bold;">优惠 {{ formatMoney(currentPromotionDetail.details.discountAmount?.amount) }}</span>
              </span>
              <span v-else-if="!currentPromotionDetail.details.stackable && currentPromotionDetail.details.thresholdUseOriginalPrice">
                购物车总额达到 {{ formatMoney(currentPromotionDetail.details.thresholdAmount?.amount) }}（原价）时，<span style="color: #e74c3c; font-weight: bold;">优惠 {{ formatMoney(currentPromotionDetail.details.discountAmount?.amount) }}</span>
              </span>
              <span v-else-if="currentPromotionDetail.details.stackable && !currentPromotionDetail.details.thresholdUseOriginalPrice">
                购物车每满 {{ formatMoney(currentPromotionDetail.details.thresholdAmount?.amount) }}（折后价），<span style="color: #e74c3c; font-weight: bold;">优惠 {{ formatMoney(currentPromotionDetail.details.discountAmount?.amount) }}</span>。
                如：购物车 {{ formatMoney(currentPromotionDetail.details.thresholdAmount?.amount * 2.5) }}，优惠2次共 {{ formatMoney(currentPromotionDetail.details.discountAmount?.amount * 2) }}
              </span>
              <span v-else>
                购物车每满 {{ formatMoney(currentPromotionDetail.details.thresholdAmount?.amount) }}（原价），<span style="color: #e74c3c; font-weight: bold;">优惠 {{ formatMoney(currentPromotionDetail.details.discountAmount?.amount) }}</span>。
                如：购物车 {{ formatMoney(currentPromotionDetail.details.thresholdAmount?.amount * 2.5) }}（原价），优惠2次共 {{ formatMoney(currentPromotionDetail.details.discountAmount?.amount * 2) }}
              </span>
            </p>
          </div>
        </div>

        <div class="modal-footer">
          <button class="btn btn-default" @click="promotionDetailModalVisible = false">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 引入依赖 -->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="/js/config.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/api.js"></script>

  <!-- 页面脚本 -->
  <script>
    const { createApp } = Vue;

    createApp({
      data() {
        return {
          activeTab: 'products',
          
          // 数据列表
          products: [],
          activeProducts: [],  // 已上架的商品（用于价格条目和促销规则选择）
          priceLists: [],
          pricingRules: [],
          units: [],
          
          // 弹窗控制
          productModalVisible: false,
          priceListModalVisible: false,
          promotionModalVisible: false,
          promotionDetailModalVisible: false,  // 促销详情弹窗
          unitModalVisible: false,
          priceEntryListModalVisible: false,
          addPriceEntryModalVisible: false,
          
          // 表单数据
          productForm: {},
          priceListForm: {},
          promotionForm: {},
          unitForm: {},
          priceEntryForm: {},
          
          // 价格条目管理相关
          currentPriceList: null,
          priceEntries: [],
          
          // 促销规则详情相关
          currentPromotionDetail: null,  // 当前查看的促销规则详情
          itemDiscountRules: [],  // 单品折扣规则列表
          thresholdDiscountRules: [],  // 满减规则列表
        };
      },
      
      mounted() {
        this.loadAllData();
      },
      
      methods: {
        /**
         * 加载所有数据
         */
        async loadAllData() {
          await Promise.all([
            this.loadProducts(),
            this.loadActiveProducts(),
            this.loadPriceLists(),
            this.loadPricingRules(),
            this.loadUnits(),
          ]);
        },
        
        // ==================== 商品管理 ====================
        
        async loadProducts() {
          try {
            // 加载所有商品（用于商品管理Tab）
            const result = await API.getProducts({ page: 0, size: 100 });
            this.products = result.data && result.data.content ? result.data.content : [];
          } catch (error) {
            showError(error);
          }
        },
        
        async loadActiveProducts() {
          try {
            // 只加载已上架的商品（用于价格条目和促销规则选择）
            const result = await API.getProducts({ 
              page: 0, 
              size: 100,
              status: 'ACTIVE'
            });
            this.activeProducts = result.data && result.data.content ? result.data.content : [];
          } catch (error) {
            showError(error);
          }
        },
        
        async openProductModal(product = null) {
          if (product) {
            // 编辑模式：从后端获取完整的商品信息（包含描述）
            try {
              const result = await API.getProductById(product.id);
              const fullProduct = result.data;
              this.productForm = {
                id: fullProduct.id,
                name: fullProduct.name || '',
                category: fullProduct.category || '',
                description: fullProduct.description || '',
              };
            } catch (error) {
              showError(error);
              return;
            }
          } else {
            // 新建模式
            this.productForm = {
              name: '',
              category: '水果',
              description: '',
            };
          }
          this.productModalVisible = true;
        },
        
        async saveProduct() {
          try {
            if (this.productForm.id) {
              // 编辑模式：只提取后端接受的字段
              const updateData = {
                name: this.productForm.name,
                category: this.productForm.category,
                description: this.productForm.description,
                // status 字段如果前端表单有编辑可以加上，目前后端接受但前端表单没有编辑状态
              };
              await API.updateProduct(this.productForm.id, updateData);
            } else {
              // 新建模式：只提取后端接受的字段
              const createData = {
                name: this.productForm.name,
                category: this.productForm.category,
                description: this.productForm.description,
                status: this.productForm.status || 'ACTIVE',
              };
              await API.createProduct(createData);
            }
            showSuccess('保存成功');
            this.productModalVisible = false;
            this.loadProducts();
            this.loadActiveProducts(); // 同步更新价目表下拉框的商品列表
          } catch (error) {
            showError(error);
          }
        },
        
        async listProduct(id) {
          try {
            await API.listProduct(id);
            showSuccess('商品已上架');
            this.loadProducts();
            this.loadActiveProducts(); // 同步更新价目表下拉框的商品列表
          } catch (error) {
            showError(error);
          }
        },
        
        async delistProduct(id) {
          if (!confirm('确定要下架该商品吗？\n\n提示：如果商品在激活的价目表中，将无法下架。')) {
            return;
          }
          try {
            await API.delistProduct(id);
            showSuccess('商品已下架');
            this.loadProducts();
            this.loadActiveProducts(); // 同步更新价目表下拉框的商品列表
          } catch (error) {
            showError(error);
          }
        },
        
        async deleteProduct(id) {
          if (!confirm('确定要删除该商品吗？')) return;
          try {
            await API.deleteProduct(id);
            showSuccess('删除成功');
            this.loadProducts();
            this.loadActiveProducts(); // 同步更新价目表下拉框的商品列表
          } catch (error) {
            showError(error);
          }
        },
        
        // ==================== 价目表管理 ====================
        
        async loadPriceLists() {
          try {
            const result = await API.getPriceLists();
            // 后端返回的是 List<PriceListSummaryDTO>，不是分页对象
            this.priceLists = result.data || [];
          } catch (error) {
            showError(error);
          }
        },
        
        openPriceListModal() {
          this.priceListForm = {
            name: '',
            effectiveFrom: '',
            effectiveTo: '',
          };
          this.priceListModalVisible = true;
        },
        
        async savePriceList() {
          try {
            // 转换日期格式：YYYY-MM-DD -> YYYY-MM-DD 00:00:00
            const requestData = {
              name: this.priceListForm.name,
              effectiveFrom: this.priceListForm.effectiveFrom ? this.priceListForm.effectiveFrom + ' 00:00:00' : null,
              effectiveTo: this.priceListForm.effectiveTo ? this.priceListForm.effectiveTo + ' 23:59:59' : null,
            };
            await API.createPriceList(requestData);
            showSuccess('价目表创建成功');
            this.priceListModalVisible = false;
            this.loadPriceLists();
          } catch (error) {
            showError(error);
          }
        },
        
        async activatePriceList(id) {
          try {
            await API.activatePriceList(id);
            showSuccess('价目表已激活');
            this.loadPriceLists();
          } catch (error) {
            showError(error);
          }
        },
        
        async deactivatePriceList(id) {
          try {
            await API.deactivatePriceList(id);
            showSuccess('价目表已停用');
            this.loadPriceLists();
          } catch (error) {
            showError(error);
          }
        },
        
        async deletePriceList(id) {
          if (!confirm('确定要删除该价目表吗？\n\n提示：激活状态的价目表无法删除，请先停用。')) {
            return;
          }
          try {
            await API.deletePriceList(id);
            showSuccess('价目表已删除');
            this.loadPriceLists();
          } catch (error) {
            showError(error);
          }
        },
        
        async viewPriceListEntries(priceList) {
          this.currentPriceList = priceList;
          this.priceEntryListModalVisible = true;
          await this.loadPriceEntries(priceList.id);
        },
        
        /**
         * 加载价格条目列表
         */
        async loadPriceEntries(priceListId) {
          try {
            const result = await API.getPriceListEntries(priceListId);
            this.priceEntries = result.data || [];
            console.log('加载价格条目:', this.priceEntries.length, '条');
          } catch (error) {
            showError(error);
            this.priceEntries = [];
          }
        },
        
        /**
         * 打开添加价格条目弹窗
         */
        async openAddEntryModal() {
          this.priceEntryForm = {
            productId: '',
            unitPrice: 0,
            baseUnit: '',
          };
          this.addPriceEntryModalVisible = true;
          
          // 打开弹窗时刷新商品列表，确保显示最新的已上架商品
          await this.loadActiveProducts();
        },
        
        /**
         * 保存价格条目
         */
        async savePriceEntry() {
          try {
            if (!this.priceEntryForm.productId) {
              throw new Error('请选择商品');
            }
            if (!this.priceEntryForm.unitPrice || this.priceEntryForm.unitPrice <= 0) {
              throw new Error('请输入有效的单价');
            }
            if (!this.priceEntryForm.baseUnit) {
              throw new Error('请选择销售单位');
            }

            const requestData = {
              productId: this.priceEntryForm.productId,
              unitPrice: this.priceEntryForm.unitPrice,
              baseUnit: this.priceEntryForm.baseUnit,
            };

            await API.addPriceListEntry(this.currentPriceList.id, requestData);
            showSuccess('商品添加成功');
            this.addPriceEntryModalVisible = false;
            // 重新加载价格条目列表
            await this.loadPriceEntries(this.currentPriceList.id);
          } catch (error) {
            showError(error);
          }
        },
        
        /**
         * 删除价格条目
         */
        async deletePriceEntry(entryId) {
          if (!confirm('确定要删除该价格条目吗？')) return;
          try {
            await API.deletePriceListEntry(this.currentPriceList.id, entryId);
            showSuccess('删除成功');
            // 重新加载价格条目列表
            await this.loadPriceEntries(this.currentPriceList.id);
          } catch (error) {
            showError(error);
          }
        },
        
        // ==================== 促销规则管理 ====================
        
        async loadPricingRules() {
          try {
            // 并行加载三个接口数据
            const [rulesResult, itemDiscountsResult, thresholdDiscountsResult] = await Promise.all([
              API.getPricingRules({ page: 0, size: 100 }),
              API.getAllItemDiscounts().catch(() => ({ data: [] })),
              API.getAllThresholdDiscounts().catch(() => ({ data: [] }))
            ]);
            
            this.pricingRules = rulesResult.data || [];
            this.itemDiscountRules = itemDiscountsResult.data || [];
            this.thresholdDiscountRules = thresholdDiscountsResult.data || [];
          } catch (error) {
            showError(error);
          }
        },
        
        openPromotionModal(ruleType) {
          this.promotionForm = {
            ruleType: ruleType,
            name: '',
            effectiveFrom: '',
            effectiveTo: '',
            productId: '',
            discountRate: 0.8,
            thresholdAmount: 100,
            reductionAmount: 10,
            stackable: false,
            thresholdUseOriginalPrice: false,  // 默认基于折后价
          };
          this.promotionModalVisible = true;
        },
        
        async savePromotion() {
          try {
            // 转换时间格式：datetime-local 格式 "2025-01-01T08:00" -> "2025-01-01 08:00:00"
            const formatDateTime = (datetimeLocal) => {
              if (!datetimeLocal) return null;
              return datetimeLocal.replace('T', ' ') + ':00';
            };
            
            if (this.promotionForm.ruleType === 'ITEM_DISCOUNT') {
              await API.createItemDiscountRule({
                name: this.promotionForm.name,
                effectiveFrom: formatDateTime(this.promotionForm.effectiveFrom),
                effectiveTo: formatDateTime(this.promotionForm.effectiveTo),
                productId: this.promotionForm.productId,
                discountRate: this.promotionForm.discountRate,
              });
            } else {
              await API.createThresholdDiscountRule({
                name: this.promotionForm.name,
                effectiveFrom: formatDateTime(this.promotionForm.effectiveFrom),
                effectiveTo: formatDateTime(this.promotionForm.effectiveTo),
                thresholdAmount: this.promotionForm.thresholdAmount,
                reductionAmount: this.promotionForm.reductionAmount,
                stackable: this.promotionForm.stackable,
                thresholdUseOriginalPrice: this.promotionForm.thresholdUseOriginalPrice,
              });
            }
            showSuccess('促销规则创建成功');
            this.promotionModalVisible = false;
            this.loadPricingRules();
          } catch (error) {
            showError(error);
          }
        },
        
        async enablePricingRule(id) {
          const rule = this.pricingRules.find(r => r.id === id);
          if (!rule) return;
          
          // 查找冲突规则（同类型、同优先级、已启用）
          const conflictRules = this.pricingRules.filter(r => 
            r.type === rule.type && 
            r.priority === rule.priority && 
            r.enabled && 
            r.id !== id
          );
          
          // 如果有冲突，提示用户
          if (conflictRules.length > 0) {
            const conflictNames = conflictRules.map(r => `"${r.name}"`).join('、');
            if (!confirm(`启用"${rule.name}"将自动禁用以下规则：\n\n${conflictNames}\n\n确认继续吗？`)) {
              return;
            }
          }
          
          try {
            await API.enablePricingRule(id);
            showSuccess('规则已启用' + (conflictRules.length > 0 ? '，冲突规则已自动禁用' : ''));
            this.loadPricingRules();
          } catch (error) {
            showError(error);
          }
        },
        
        async disablePricingRule(id) {
          try {
            await API.disablePricingRule(id);
            showSuccess('规则已禁用');
            this.loadPricingRules();
          } catch (error) {
            showError(error);
          }
        },
        
        async deletePricingRule(id) {
          if (!confirm('确定要删除该规则吗？')) return;
          try {
            await API.deletePricingRule(id);
            showSuccess('删除成功');
            this.loadPricingRules();
          } catch (error) {
            showError(error);
          }
        },
        
        /**
         * 打开促销规则详情弹窗
         */
        async openPromotionDetailModal(rule) {
          try {
            // 复制基本信息
            this.currentPromotionDetail = { ...rule };
            
            // 根据规则类型，关联详细信息
            if (rule.type === 'ITEM_DISCOUNT') {
              // 查找对应的单品折扣详情
              const itemDetail = this.itemDiscountRules.find(item => item.pricingRuleId === rule.id);
              if (itemDetail) {
                this.currentPromotionDetail.details = itemDetail;
                
                // 如果有商品ID但没有商品名称，尝试查找商品名称
                if (itemDetail.productId && !itemDetail.productName) {
                  const product = this.activeProducts.find(p => p.id === itemDetail.productId);
                  if (product) {
                    this.currentPromotionDetail.details.productName = product.name;
                  }
                }
              }
            } else if (rule.type === 'THRESHOLD_DISCOUNT') {
              // 查找对应的满减规则详情
              const thresholdDetail = this.thresholdDiscountRules.find(item => item.pricingRuleId === rule.id);
              if (thresholdDetail) {
                this.currentPromotionDetail.details = thresholdDetail;
              }
            }
            
            this.promotionDetailModalVisible = true;
          } catch (error) {
            showError(error);
          }
        },
        
        // ==================== 单位管理 ====================
        
        async loadUnits() {
          try {
            const result = await API.getAllUnits();
            this.units = result.data || [];
          } catch (error) {
            showError(error);
          }
        },
        
        openUnitModal(unit = null) {
          if (unit) {
            this.unitForm = { ...unit };
          } else {
            this.unitForm = {
              code: '',
              name: '',
              description: '',
            };
          }
          this.unitModalVisible = true;
        },
        
        async saveUnit() {
          try {
            if (!this.unitForm.code) {
              throw new Error('请输入单位代码');
            }
            await API.createUnit(this.unitForm);
            showSuccess('保存成功');
            this.unitModalVisible = false;
            this.loadUnits();
          } catch (error) {
            showError(error);
          }
        },
        
        async deleteUnit(code) {
          if (!confirm('确定要删除该单位吗？')) return;
          try {
            await API.deleteUnit(code);
            showSuccess('删除成功');
            this.loadUnits();
          } catch (error) {
            showError(error);
          }
        },
        
        // ==================== 工具方法 ====================
        
        formatDateTime(datetime, format) {
          return formatDateTime(datetime, format);
        },
        
        /**
         * 格式化金额
         */
        formatMoney(amount) {
          if (amount === null || amount === undefined) return '0.00';
          return formatMoney(amount);
        },
        
        /**
         * 获取优先级说明
         */
        getPriorityDescription(priority) {
          const priorityMap = {
            1: '商品级（最优先）',
            2: '组合优惠',
            3: '订单级',
            4: '用户级'
          };
          return priorityMap[priority] || '未知';
        },
      }
    }).mount('#app');
  </script>
</body>
</html>

